package com.java.hohenheim.springplatform.web.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.java.hohenheim.springplatform.data.web.FailRespModel;
import com.java.hohenheim.springplatform.define.ResultCodes;
import com.java.hohenheim.springplatform.web.ResultPackWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Hohenheim
 * @date 2020/9/3
 * @description
 */
@Slf4j
public abstract class BaseUserAccessControlFilter extends AccessControlFilter {
    protected final ObjectMapper mJsonMapper;

    public BaseUserAccessControlFilter() {
        mJsonMapper = new ObjectMapper();
    }

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        httpResponse.setHeader("Access-control-Allow-Origin", httpRequest.getHeader("Origin"));
        httpResponse.setHeader("Access-Control-Allow-Methods","GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Headers", httpRequest.getHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS));

        if (httpRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpResponse.setStatus(HttpStatus.OK.value());
            return true;
        }

        return super.preHandle(request, response);
    }

    protected void responseResult(ResultCodes result, ServletResponse response) {
        responseResult(result.getCode(), result.getMsg(), response);
    }

    protected void responseResult(int code, String msg, ServletResponse response) {
        try {
            HttpServletResponse resp = (HttpServletResponse) response;
            resp.setContentType("application/json");
            resp.setCharacterEncoding("UTF-8");
            resp.setStatus(HttpStatus.UNAUTHORIZED.value());

            FailRespModel<Object> respModel = ResultPackWrapper.reqFail(code, msg);

            PrintWriter out = resp.getWriter();
            out.write(mJsonMapper.writeValueAsString(respModel));
            out.flush();
            out.close();
        }
        catch (IOException e) {
            log.error("Token校验失败信息响应失败", e);
        }
    }
}
